import Router from '@koa/router';
import XLSX  from 'xlsx';
import fs from 'fs';
import { BeError, BeSuccess } from '../utils/response';
import { GetTaskList, AddTask, GetTask, UpdateTask } from '../services/appointTask';
import MusenumUserModel from "../model/musenumUser";
import { gainAllSystemConfigLogin } from '../thirdServices/museumApi';
import { getCalendartickt, getCanBuyDays } from '../thirdServices/palaceApi'
import { isMuseumPoolAvailable } from '../utils';
import MuseumHelper from '../middleware/museumHelper';
import PalaceHelper from '../middleware/palaceHelper';
import log from '../utils/log';
import { museumIdTypeMap, museumTimeMap, palaceIdTypeMap, placeTimeMap } from '../config/variables';

const router = new Router();

const getTicketPool = async (appointDate, appointTime) => {
  const model = await MusenumUserModel.findOneAvailable();
  let ticketPool;
  if (model) {
    const token = model.getDataValue('token');
    const res = await gainAllSystemConfigLogin(token);
    if (res.data.code === 200) {
      // status 3 无票 0 闭馆  -1 暂未放票 4 有票 
      // ticketPool 剩余票数
      const list: any[] = res.data.data.calendarTicketPoolsByDate;
      for (let i = 0; i< list.length; i++) {
        const ticket = list[i];
        if (isMuseumPoolAvailable(ticket)) {
          const hallTicketPoolVOS = ticket.hallTicketPoolVOS[0].scheduleTicketPoolVOS
          for (let j = 0; j < hallTicketPoolVOS.length; j++) {
            const poolVO = hallTicketPoolVOS[j];
            if (isMuseumPoolAvailable(poolVO)) {
              if (appointTime != undefined) {
                // 指定日期+时间
                const ticketDate = `${ticket.currentDate}-${poolVO.hallScheduleId}`;
                const ticketDateStr = `${appointDate}-${appointTime}`;
                // 有需求
                if (ticketDate === ticketDateStr) {
                  ticketPool = poolVO;
                }
              } else {
                // 指定日期
                const ticketDate = `${ticket.currentDate}`;
                const ticketDateStr = `${appointDate}`;
                // 有需求
                if (ticketDate === ticketDateStr) {
                  ticketPool = poolVO;
                }
              }
            }
          }
        }
      }
    }
  }

  return ticketPool;
}

const getPalaceTicketPool = async (appointDate, appointTime) => {
  let ticketPool;
  const res = await getCanBuyDays();
  if (res.data.code === 200) {
    const canJson = JSON.parse(res.data.data);
    const date = new Date(canJson.time);
    const dateList: string[] = [];
    for (let i = 0;i< canJson.days; i++) {
        let day = date.getDate();
        date.setDate(day + 1);
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const monthStr = month < 10 ? `0${month}` : `${month}`
        const d = date.getDate();
        const dStr = d < 10  ? `0${d}` : `${d}`;
        dateList.push(`${year}-${monthStr}-${dStr}`);
    }
    
    if (dateList.includes(appointDate)) {
      const date = new Date(appointDate);
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const monthStr = month < 10 ? `0${month}` : `${month}`
      const params = {
        parkId: 11324,
        year,
        month: monthStr,
        merchantId: 2655,
        merchantInfoId: 2655
      };

      const calendarRes = await getCalendartickt(params);

      if (calendarRes.data.status === 200) {
        const calendarList = calendarRes.data.data;
        const vo = calendarList.find(item => item.occDate === appointDate);
        if (vo.saleStatus === 'T') {
          if (vo.parkFsyyDetailDTOS) {
            if (appointTime != undefined) {
              // 指定时间段
              const dto = vo.parkFsyyDetailDTOS[appointTime - 1];
              if (dto.stockNum) {
                ticketPool = vo;
                ticketPool.DTO = dto;
              }
            } else {
              // 不指定时间段
              const dto = vo.parkFsyyDetailDTOS.find(dto => !!dto.stockNum);
              if (dto) {
                ticketPool = vo;
                ticketPool.DTO = dto;
              }
            }
          }
        } else {
          console.log('闭馆');
        }
      }
    }
  }
  return ticketPool;
}

const createTicket = async (poolVO, touristList) => {
  const museumHelper = new MuseumHelper();
  const isBuy = await museumHelper.buy(poolVO, touristList);
  return isBuy;
};

const createPalaceTicket = async (poolVO, touristList) => {
  const palaceHelper = new PalaceHelper();
  const isBuy = await palaceHelper.buy(poolVO, touristList);
  return isBuy;
};

// 任务列表
router.get('/list', async function (ctx) {
  const { page, platform } = ctx.query;
  try {
    const data = await GetTaskList(page, platform);
    ctx.body = BeSuccess(data);
  } catch (error) {
    console.log(error);
    ctx.body = BeError(error.message);
  }
});

// 添加任务
router.post('/add', async function (ctx) {
  const { appointDate, platform, appointTime, touristList } = ctx.request.body;
  if (touristList.length > 5) {
    ctx.body = BeError('最多只能添加5个');
    return;
  };

  try {
    if (platform === 1) {
      const isBuy = await buyMuseumTicket(appointDate, appointTime, touristList);
      log.debug('【博物馆】：' + (isBuy ? '购票成功' : '购票失败' ));
      if (isBuy) {
        ctx.body = BeSuccess('ok', '购买成功');
        return;
      }
    } else if (platform === 2) {
      const isBuy = await buyPalaceTicket(appointDate, appointTime, touristList);
      log.debug('【故宫】：' + (isBuy ? '购票成功' : '购票失败' ));
      if (isBuy) {
        ctx.body = BeSuccess('ok', '购买成功');
        return;
      }
    }

    await AddTask(platform, appointDate, appointTime, JSON.stringify(touristList), touristList.length);
    log.debug('【任务】：添加任务');
    ctx.body = BeSuccess('ok', '添加任务成功');
  } catch (error) {
    console.log(error);
    ctx.body = BeError(error.message);
  }
});

/**
 * 故宫
 */
router.post('/importExcelMuseum', async function (ctx) {
  const file = ctx.request.files.file;
  if (!file) {
    ctx.body = BeError('没有文件', 405);
    return;
  }
  const buffer = fs.readFileSync(file.filepath);
  

  // 使用 xlsx 库解析文件内容
  const workbook = XLSX.read(buffer, { type: 'buffer' });

  const sheetName = workbook.SheetNames[0];
  const worksheet = workbook.Sheets[sheetName];

  // 将工作表转换为 JSON 对象数组
  const jsonData = XLSX.utils.sheet_to_json(worksheet, {raw: false});
  
  const list = jsonData.map((item: any) => {
    return {
      appointDate: item['预约日期'],
      appointTime: museumTimeMap[item['预约时段']],
      touristList: [{
        name: item['游客姓名'],
        idType: museumIdTypeMap[item['证件类型']],
        idNo: item['证件号码'],
      }]
    }
  });

  const arr = list.map((item: any) => {
    return AddTask('1', item.appointDate, item.appointTime, JSON.stringify(item.touristList), 1);
  });

  try {
    await Promise.all(arr);
    ctx.body = BeSuccess('ok', '添加任务成功');
  } catch (error) {
    console.log(error);
    ctx.body = BeError(error.message);
  }
});

/**
 * 博物馆
 */
router.post('/importExcelPlace', async function (ctx) {
  const file = ctx.request.files.file;
  if (!file) {
    ctx.body = BeError('没有文件', 405);
    return;
  }
  const buffer = fs.readFileSync(file.filepath);
  
  // 使用 xlsx 库解析文件内容
  const workbook = XLSX.read(buffer, { type: 'buffer' });

  const sheetName = workbook.SheetNames[0];
  const worksheet = workbook.Sheets[sheetName];

  // 将工作表转换为 JSON 对象数组
  const jsonData = XLSX.utils.sheet_to_json(worksheet, {raw: false});
  
  const list = jsonData.map((item: any) => {
    return {
      appointDate: item['预约日期'],
      appointTime: placeTimeMap[item['预约时段']],
      touristList: [{
        name: item['游客姓名'],
        idType: palaceIdTypeMap[item['证件类型']],
        idNo: item['证件号码'],
        ticketType: item['预约票种']
      }]
    }
  });

  const arr = list.map((item: any) => {
    return AddTask('2', item.appointDate, item.appointTime, JSON.stringify(item.touristList), 1);
  });

  try {
    await Promise.all(arr);
    ctx.body = BeSuccess('ok', '添加任务成功');
  } catch (error) {
    console.log(error);
    ctx.body = BeError(error.message);
  }
});

const buyMuseumTicket = async  (appointDate, appointTime, touristList) => {
  // `${appointDate}-${appointTime}`
  const ticketPool = await getTicketPool(appointDate, appointTime);
  let isBuy = false;
  if (ticketPool) {
    try {
      isBuy = await createTicket(ticketPool, touristList);
    } catch (error) {
      
    }
  }

  return isBuy;
}

const buyPalaceTicket = async (appointDate, appointTime, touristList) => {
  const ticketPool = await getPalaceTicketPool(appointDate, appointTime);
  let isBuy = false;
  if (ticketPool) {
    log.debug('【故宫】：有票');
    try {
      isBuy = await createPalaceTicket(ticketPool, touristList);
    } catch (error) {
      
    }
  }
  return isBuy;
}


router.post('/updateStatus', async function (ctx) {
  const { id, status } = ctx.request.body;

  try {
    const info = await GetTask(id);
    if (!info) {
      throw new Error('任务不存在');
    }

    if (status === 1) {
      // throw new Error('时间已过，不能启动');
    }
    info.status = status;
    const data = await UpdateTask({ status }, id);
    ctx.body = BeSuccess(data);
  } catch (error) {
    console.log(error);
    ctx.body = BeError(error.message);
  }
});

export default router.routes();
